LeetCode Js-258. Add Digits
Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.
給予一個整數 num,重複相加所有的數字直到結果只有個位數,並回傳該值。
ex. Input: nums = 18
18 = 1 + 8 --> 9
return 9
Example 1:
Input: num = 38
Output: 2
Explanation: The process is
38 --> 3 + 8 --> 11
11 --> 1 + 1 --> 2
Since 2 has only one digit, return it.
Solution:
如果 num 介於 0 ~ 9 之間,回傳 num。
當 (num > 9)時宣告 sum = 0,且
當 (num 的整數不等於 0),
執行以下:
(1.) sum = 0 + 個位數
(2.) num = num / 10
將 num = sum,回傳 num。
Code:
var addDigits = function(num) {
if (num < 10 && num >= 0) return num
while (num > 9) {
let sum = 0
while (parseInt(num) !== 0) {
sum += parseInt(num % 10)
num /= 10
}
num = sum
}
return num
};
FlowChart:
Example 1
Input: num = 38
38 !== 0
--> 3 + 8 --> 11
11 !== 0
--> 1 + 1 --> 2
2 < 9, return 2